package cn.nju.zyy.service.person;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import cn.nju.zyy.model.person.Person;

@Component
public class PersonService {

	private static final Logger logger = Logger.getLogger(PersonService.class
			.getName());

	private static SortedMap<Integer, Person> personMap = new TreeMap<Integer, Person>();

	static {
		personMap.put(1, new Person(1, "Zhang", "San", "zs@gmail.com",
				"123-456-7890", "football", "male", "KS", true,
				new String[] { "Ford" }));
		personMap.put(2, new Person(2, "Li", "Si", "ls@gmail.com",
				"111-111-1111", "baseball", "female", "AZ", true,
				new String[] { "Nissan" }));
	}

	private static List<Person> personList = new ArrayList<Person>();

	static {
		for (Integer id : personMap.keySet()) {
			personList.add(personMap.get(id));
		}
	}

	public static List<Person> getPersonList() {
		return personList;
	}

	public void save(Person person) {
		int newId = getNewId();
		person.setId(newId);
		personMap.put(newId, person);
		rebuildPersonList();
	}

	public Person getPerson(int id) {
		return personMap.get(id);
	}

	public void update(Person person) {
		Person tempPerson = personMap.get(person.getId());

		tempPerson.setFirstName(person.getFirstName());
		tempPerson.setLastName(person.getLastName());
		tempPerson.setEmail(person.getEmail());
		tempPerson.setPhoneNumber(person.getPhoneNumber());
		tempPerson.setSport(person.getSport());
		tempPerson.setGender(person.getGender());
		tempPerson.setResidency(person.getResidency());
		tempPerson.setOver21(person.isOver21());
		tempPerson.setCarModels(person.getCarModels());

		rebuildPersonList();
	}

	public void delete(int id) {
		personMap.remove(id);
		rebuildPersonList();
	}

	private int getNewId() {
		int newId = 0;
		try {
			newId = personMap.lastKey() + 1;
		} catch (NoSuchElementException ex) {
			logger.info("Id value set to 0");
		}
		return newId;
	}

	private static void rebuildPersonList() {
		personList.clear();
		for (Integer id : personMap.keySet()) {
			personList.add(personMap.get(id));
		}
	}

}
